<?php

namespace app\api\controller\user;

use app\admin\model\user\User;
use app\api\controller\Base;
use app\common\service\lib\Jwt;
use app\common\service\lib\Mac;
use app\common\service\lib\Sign;
use app\common\service\lib\sms\Sms;
use app\common\service\lib\sms\SmsRongLian;
use app\common\service\lib\sms\SmsTreasure;
use app\common\service\user\LoginService;
use app\validate\PhoneLogin;
use app\validate\PhoneRegister;
use think\exception\ValidateException;
use think\facade\Cache;
use think\Response;

class Login extends Base
{
    /**
     * Author:Zhongyuan Lu
     * 获取token
     */
    public function login()
    {
        $uid = $this->request->param('uid');
        $data = [];
        if ($uid) {
            $data['id'] = $uid;
        }

        $token = Jwt::signToken($data);
        return $this->result(['code' => 200, 'token' => $token, 'message' => '登录'],200,'获取token');
    }

    /**
     * Author:Zhongyuan Lu
     * 通过手机号 发送验证码
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function sendSms()
    {
        if (!$this->request->isPost()) {
            return $this->result([], 400, '请求方式错误');
        }
        $phone = $this->request->post('phone', 0, 'trim');

        if (empty($phone)) {
            return $this->result([], 400, '请输入手机号');
        }
        //正则验证手机号
        if (!checkMobile($phone)) {
            return $this->result([], 400, '手机号错误');
        }

        $redis = Cache::store('redis');
        $redis->select(1);


        //60秒内只能获取一次验证码
        if ($redis->get("{$phone}:code:disableTime")) {
            return $this->result([], 400, '60秒之内不能再次获取验证码');
        }

        if ($redis->get("{$phone}:code:count") > 15) {
            return $this->result([], 400, '今日发送验证码已达上限，请明天重试');
        }


            //生成验证码
        $code = verifyCode();

        $data = Sms::sendSms($phone, $code);

        if ($data['code'] == 200) {
            //redis 存储验证码   和   60秒内是否已发送验证码
            $redis->set("{$phone}:code", $code,120);
            $redis->set("{$phone}:code:disableTime",60,60);
            if (!$redis->has("{$phone}:code:count")) {
                $time = strtotime(date('Y-m-d 23:59:59',time())) - time();
                $redis->set("{$phone}:code:count",1,$time);
            }else {
                $redis->incr("{$phone}:code:count");
            }

            return $this->result($data, 200, '发送成功');
        }
        return $this->result($data, 400, '发送失败');
    }

    /**
     * Author:Zhongyuan Lu
     * 手机号注册
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function phoneRegister()
    {
        if (!$this->request->isPost()) {
            return $this->result([], 400, '请求方式错误');
        }
        $params['phone'] = $this->request->post('phone', 0, 'trim');
        $params['code'] = $this->request->post('code', 0, 'trim');
        $params['password'] = $this->request->post('password', '', 'trim');

        //验证参数
        $this->validateFail(PhoneRegister::class,$params);

        $redis = Cache::store('redis');
        $redis->select(1);

        $verifyCode = $redis->get("{$params['phone']}:code");
        if ($verifyCode !== $params['code']) {
            return $this->result([], 400, '验证码错误');
        }
        unset($params['code']);

        $data = LoginService::register($params);
        return $this->res($data);
    }

    /**
     * Author:Zhongyuan Lu
     * 手机号密码登录
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function PhoneLogin()
    {
        if (!$this->request->isPost()) {
            return $this->result([], 400, '请求方式错误');
        }
        //接收参数
        $params['phone'] = $this->request->post('phone', 0, 'trim');
        $params['password'] = $this->request->post('password', 0, 'trim');

        //验证参数
        $this->validateFail(PhoneLogin::class,$params);

        $redis = Cache::store('redis');
        $redis->select(1);

        //如果5分钟内错误次数过多   限制用户继续登录  5分钟后重试
        if ($redis->get("{$params['phone']}:login:error")) {
            $message = "密码错误次数过多，请{$redis->ttl("{$params['phone']}:login:error")}秒后重试";
            return $this->result([], 400, $message);
        }
        //获取用户信息，比对密码
        $data = LoginService::PhoneLogin($params);

        if ($data['code'] == 200) {
            $data['token'] = Jwt::signToken($data['data']);
            return Response::create($data,'json',200);
        }
        //密码错误   记录错误次数  如果错误5次以后  限制用户登录   5分钟之后重试
        $redis->incr("{$params['phone']}:login:count");
        $redis->expire("{$params['phone']}:login:count",300);
        if ($redis->get("{$params['phone']}:login:count") >= 5) {
            $redis->set("{$params['phone']}:login:error",1,300);
        }
        return $this->result([], 400, $data['message']);
    }
}